package com.zhangyt.client.api;

import com.alibaba.fastjson2.JSON;
import com.zhangyt.client.conf.MqttProps;
import com.zhangyt.client.service.MqttService;
import com.zhangyt.client.utils.TransformerUtils;
import com.zhangyt.mqtt.message.ChargePayload;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 发送消息的api  payload
 */
@RestController
@Slf4j
public class SendApi {

    @Resource
    private MqttProps props;


    @Resource
    private MqttService gateWay;

    /**
     * 发送消息
     * @param message
     */
    @PostMapping("/mqtt/send")
    String doSend(@RequestBody ChargePayload message){
        //将message转换为16进制，再转为字节数组
        /* **********************
         *
         * 发送16进制报文：
         *
         * 思路：将16进制的字符串转换为字节数组
         *      MQTT客户端将字节数组发送出去
         *
         *
         * 1. 将ChargePayload转换为16进制字符串
         * 2. 将16进制的字符串转换为字节数组
         * 3. 字节数组包装成Message对象
         *
         * *********************/
        //1. 将ChargePayload转换为16进制字符串
        String hex = TransformerUtils.objectToHex(message);
        //2. 将16进制的字符串转换为字节数组
        byte[] bytes = TransformerUtils.hexStringToByteArray(hex);
        Message<byte[]> bytesArray = MessageBuilder.withPayload(bytes).build();

    
        
        //MQTT发送16进制报文
        gateWay.send(props.getTopic(),bytesArray);
        //最简单的方式是转成json字符串发送
//        gateWay.send(props.getTopic(), JSON.toJSONString(message));
        //mqtt消息转换器默认只能接收string和byte[]
//        gateWay.send(props.getTopic(), message);
        return "send success";
    }



}
